<template lang="pug">
  div.choose-image
    slot
    .images(ref="boxWrapper",v-show="images.length && !$slots.default")
      div
        section(v-for="(item,key) in images",:key="key",@click="removeImage(key)")
          img(:src="item")
    div.control(:class="{is_slot: $slots.default}")
      label(@click="$helper.isWechat ? selectImageOnWechat() : ''")
        input(v-if="!$helper.isWechat",type="file",@change="selectImageOnWeb($event)")
</template>

<script>
import { Toast } from 'mint-ui'
import BScroll from 'better-scroll'
export default {
  props: {
    count: {
      type: Number,
      default: 5
    }
  },
  data () {
    return {
      boxScroll: null,
      images: []
    }
  },
  mounted () {
    this.$nextTick(() => {
      this._initScroll()
    })
  },
  watch: {
    images: {
      handler: function (val, oldval) {
        this.$nextTick(() => {
          this._initScroll()
        })
        this.$emit('change', this.count === 1 && val.length > 0 ? val[val.length - 1] : val)
      },
      immediate: false,
      deep: true
    }
  },
  methods: {
    _initScroll () {
      let sectionEl = this.$refs.boxWrapper.getElementsByTagName('section')
      this.$refs.boxWrapper.getElementsByTagName('div')[0].style['width'] = (sectionEl.length * (2.6 + 0.4)) + 'rem'
      if (!this.boxScroll) {
        this.$nextTick(() => {
          this.boxScroll = new BScroll(this.$refs.boxWrapper, {
            probeType: 1,
            click: false,
            scrollY: false,
            scrollX: true
          })
          this.boxScroll.on('scrollStart', () => {
            this.scrolling = true
          })
          this.boxScroll.on('scrollEnd', () => {
            this.scrolling = false
          })
        })
      } else {
        this.boxScroll.refresh()
      }
    },
    canvasDataURL (path, obj, callback) {
      let img = new Image()
      img.src = path
      img.onload = function () {
        let that = this
        // 默认按比例压缩
        let w = that.width
        let h = that.height
        let scale = w / h
        w = obj.width || w
        h = obj.height || (w / scale)
        let quality = 0.7 // 默认图片质量为0.7
        // 生成canvas
        let canvas = document.createElement('canvas')
        let ctx = canvas.getContext('2d')
        // 创建属性节点
        let anw = document.createAttribute('width')
        anw.nodeValue = w
        let anh = document.createAttribute('height')
        anh.nodeValue = h
        canvas.setAttributeNode(anw)
        canvas.setAttributeNode(anh)
        ctx.drawImage(that, 0, 0, w, h)
        // 图像质量
        if (obj.quality && obj.quality <= 1 && obj.quality > 0) {
          quality = obj.quality
        }
        // quality值越小，所绘制出的图像越模糊
        let base64 = canvas.toDataURL('image/jpeg', quality)
        // 回调函数返回base64的值
        callback(base64)
      }
    },
    photoCompress (file, w, objDiv) {
      let ready = new FileReader()
      ready.readAsDataURL(file)
      ready.onload = () => {
        let re = this.result
        this.canvasDataURL(re, w, objDiv)
      }
    },
    removeImage (key) {
      this.images.splice(key, 1)
    },
    selectImageOnWeb (e) {
      if (this.images.length >= this.count) {
        return Toast('图片数量不能大于 ' + this.count + ' 个')
      }
      let file = e.target
      if (!file.files || !file.files[0]) {
        return
      }
      let fileObj = file.files[0]
      if (fileObj.size / 1024 > 1025) {
        this.photoCompress(fileObj, {
          quality: 0.4
        }, (base64Codes) => {
          this.images.push(base64Codes)
        })
      } else {
        let reader = new FileReader()
        reader.onload = (evt) => {
          this.images.push(evt.target.result)
        }
        reader.readAsDataURL(fileObj)
      }
    },
    selectImageOnWechat () {
      if (this.images.length >= this.count) {
        return Toast('图片数量不能大于 ' + this.count + ' 个')
      }
      window.wx.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          window.wx.getLocalImgData({
            localId: res.localIds[0],
            success: (res) => {
              let localData = res.localData
              if (window.__wxjs_is_wkwebview) {
                this.images.push(localData)
              } else {
                this.images.push('data:image/jgp;base64,' + localData)
              }
            }
          })
        }
      })
    }
  }
}
</script>
<style lang="stylus" scoped>
.choose-image
  position: relative
.images
  padding: .2rem
  box-sizing: border-box
  width: 100%
  height: 2.8rem
  border-top: 1px solid #eee
  border-bottom: 1px solid #eee
  display: inline-block
  background: #fff
  overflow: hidden
  section
    border: 1px solid #eee
    float: left
    height: 2.3rem
    width: 2.6rem
    text-align: center
    margin: .1rem .2rem
    border-radius: .1rem
    overflow: hidden
    background: #efefef
  img
    width: 80%
    height: auto
.control
  label
    height: 1rem
    display: inline-block
    background: #fff
    border: 1px solid #ccc
    border-radius: .2rem
    float: left
    margin: .1rem 1rem
    cursor: pointer
    padding: 0 .5rem
    margin-right: 0
    &::before
      content: '选择图片'
      font-size: .4rem
      line-height: 1rem
    input
      display: none
.control.is_slot
  label
    width: 100%
    height: 100%
    background: rgba(255, 255, 255, 0)
    position: absolute
    top: 0
    left: 0
    margin: 0
    border-radius: 0
    padding: 0
    border: none
    &::before
      display: none
</style>
